<template>
  <el-dialog
    :title="material.filename"
    :visible.sync="visible"
    width="70%"
    top="5vh"
    :modal="false"
  >
    <el-descriptions :column="2" border>
      <el-descriptions-item label="材料编号">{{ material.id }}</el-descriptions-item>
      <el-descriptions-item label="所属人员">{{ material.aac003 }}</el-descriptions-item>
      <el-descriptions-item label="业务类型">
        <el-select v-model="material.aaa121" filterable allow-create :disabled="true">
          <el-option
            v-for="item in dict.aaa121"
            :key="item.id"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">{{ material.aae036 }}</el-descriptions-item>
    </el-descriptions>

    <el-divider />

    <h4>材料文件</h4>
    <!--    <el-table :data="material.files" style="width: 100%">-->
    <!--      <el-table-column prop="name" label="文件名"></el-table-column>-->
    <!--      <el-table-column label="操作" width="120">-->
    <!--        <template slot-scope="scope">-->
    <!--          <el-button-->
    <!--            size="mini"-->
    <!--            @click="handlePreview(scope.row)"-->
    <!--          >预览</el-button>-->
    <!--        </template>-->
    <!--      </el-table-column>-->
    <!--    </el-table>-->
    <content-block>
      <div style="margin-top: 20px;">
        <h4>文件预览 - {{ material.filename }}</h4>

        <!-- 图片预览 -->
        <!--      <img-->
        <!--        v-if="previewType === 'image'"-->
        <!--        :src="material.base64"-->
        <!--        @error="onImageError"-->
        <!--        style="max-width: 100%; max-height: 500px; display: block; margin: 0 auto;"-->
        <!--      />-->

        <!-- 图片预览 -->
        <!--        <embed-->
        <!--          v-if="previewType === 'image'"-->
        <!--          :src="material.base64"-->
        <!--          type="application/pdf"-->
        <!--          width="100%"-->
        <!--          height="600px"-->
        <!--        >-->
        <img
          v-if="previewType === 'image'"
          :src="material.base64"
          style="
                  width: 100%;
                  height: 100%;
                  object-fit: contain;"
          width="100%"
          height="600px"
        >
        <!-- pdf预览 -->
        <embed
          v-else-if="previewType === 'pdf'"
          :src="pdfUrl(material)"
          type="application/pdf"
          width="100%"
          height="600px"
        >

        <!-- Office文档预览 -->
        <iframe
          v-else-if="['doc', 'docx', 'xls', 'xlsx'].includes(previewType)"
          :src="material.base64"
          frameborder="0"
        />
        <!-- 不支持预览的格式 -->
        <div v-else class="unsupported-preview">
          <i class="el-icon-document" style="font-size: 50px; color: #909399;" />
          <p>该文件格式不支持在线预览，请下载后查看</p>
          <el-button type="primary" @click="downloadFile(material.filepath, material.filename)">
            <i class="el-icon-download" /> 下载文件
          </el-button>
        </div>
        <div v-if="['doc', 'docx', 'xls', 'xlsx'].includes(previewType)" class="unsupported-preview">
          <i class="el-icon-document" style="font-size: 50px; color: #909399;" />
          <p>该文件格式不支持在线预览，请在下载中查看</p>
        </div>
        <!--      <embed-->
        <!--        v-else-if="['doc', 'docx', 'xls', 'xlsx'].includes(previewType)"-->
        <!--        :src="material.base64"-->
        <!--        type="application/pdf"-->
        <!--        width="100%"-->
        <!--        height="600px"-->
        <!--      />-->

      </div>
    </content-block>
  </el-dialog>
</template>

<script>
import ContentBlock from '@/components/labers/contentBlock'
export default {
  name: 'MaterialPreviewDialog',
  components: { ContentBlock },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    material: {
      type: Object,
      default: () => ({})
    }
  },
  // 数据字典
  dicts: ['aaa121'],
  data() {
    return {
      previewVisible: false,
      currentFile: null,
      previewType: ''
    }
  },
  watch: {
    visible(val) {
      if (!val) {
        this.previewVisible = false
        this.fnGb()
        this.currentFile = null
      } else {
        this.handlePreview()
      }
    }
  },
  mounted() {
    this.handlePreview()
  },
  methods: {
    pdfUrl(row) {
      // 假设 row.content 是 PDF 文件的 ArrayBuffer 或 Blob 对象
      // 如果后端传的是base64，需要先转换为Blob
      let blob
      if (row.content instanceof Blob) {
        blob = row.content
      } else if (row.base64) {
        // 如果只有base64，则需要转换
        const byteCharacters = atob(row.base64.split(',')[1])
        const byteNumbers = new Array(byteCharacters.length)
        for (let i = 0; i < byteCharacters.length; i++) {
          byteNumbers[i] = byteCharacters.charCodeAt(i)
        }
        const byteArray = new Uint8Array(byteNumbers)
        blob = new Blob([byteArray], { type: 'application/pdf' })
      } else {
        // 如果没有可用数据，返回空字符串或处理错误
        return ''
      }
      return URL.createObjectURL(blob)
    },
    // 关闭
    fnGb() {
      this.visible = false
      this.$emit('gbCallBack')
    },
    // 预览文件
    handlePreview() {
      this.previewType = this.getFileType(this.material.filename)
      console.log(this.previewType, '0000000000000')
      this.$nextTick(() => {
        this.previewVisible = true
      })
    },

    // 下载文件
    downloadFile(url, fileName) {
      const a = document.createElement('a')
      a.href = url
      a.download = fileName
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    },
    onImageError() {
      // 重新加载或显示占位图
      // fileupload.getBase64({ ...this.material }).then(res => {
      //   this.material.base64 = res
      // })
    },
    // 获取文件类型
    getFileType(filename) {
      const extension = filename.split('.').pop().toLowerCase()
      if (['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(extension)) {
        console.log(this.material, 'this.material')
        return 'image'
      } else if (extension === 'pdf') {
        return 'pdf'
      } else if (['doc', 'docx'].includes(extension)) {
        return 'doc'
      } else if (['xls', 'xlsx'].includes(extension)) {
        return 'xls'
      } else {
        return 'other'
      }
    }
  }
}
</script>

<style scoped>
.unsupported-preview {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.unsupported-preview p {
  margin: 15px 0;
}
/* 确保子弹窗的z-index高于父弹窗及其遮罩层 */
.material-preview-dialog {
  z-index: 99
}
</style>
